package cn.itsource.pet.service.impl;

import ch.qos.logback.core.joran.conditional.ElseAction;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.BaiduAuditUtils;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.PetDetail;
import cn.itsource.pet.domain.PetOnlineAuditLog;
import cn.itsource.pet.mapper.PetDetailMapper;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.PetOnlineAuditLogMapper;
import cn.itsource.pet.service.IPetService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mochen
 * @since 2023-01-31
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    public void add(Pet pet) {
        super.add(pet);

        PetDetail detail = pet.getDetail();
        detail.setPetId(pet.getId());

        petDetailMapper.save(pet.getDetail());
    }

    @Override
    public AjaxResult onsaleOrOffsale(List<Long> ids, int i) {

        /*上架
        * 1.通过id循环遍历宠物信息
        * 2.百度审核宠物信息
        *       2.1未通过--->记录审核日志
        *       2.2通过--->修改状态
        *
        * */
        if (i==1){
            for (Long id : ids) {
                Pet pet = petMapper.loadById(id);

                StringBuilder sb = new StringBuilder();

                Boolean auditResult = BaiduAuditUtils.TextCensor(pet.getName());

                if (!auditResult){
                    sb.append("宠物名字:"+pet.getName()+"不合法");
                }

                if (sb.length()>0){

                    PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
                    petOnlineAuditLog.setAuditTime(new Date());
                    petOnlineAuditLog.setPetId(pet.getId());
                    petOnlineAuditLog.setState(0);
                    petOnlineAuditLog.setNote(sb.toString());
                    petOnlineAuditLogMapper.save(petOnlineAuditLog);
                    continue;

                }
                //审核通过
                Map<String,Object> params = new HashMap<>();
                params.put("id",id);
                params.put("onsaletime",new Date());
                petMapper.onsale(params);

            }
        }
        //下架  -修改state为0 offsale time为当前时间 ,可以用批量操作
        else{
            Map<String,Object> params = new HashMap<>();
            params.put("ids",ids);
            params.put("offsaletime",new Date());
            petMapper.offsale(params);
        }
        return AjaxResult.me();
    }
}
